package com.newsee.remote.ecommerce.commerce.jingdong.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.newsee.remote.common.dto.ecommerce.jingdong.JDtokenDTO;
import com.newsee.remote.common.enumeration.EcommerceEnum;
import com.newsee.remote.common.utils.ecache.ConcurrentHashMapCacheUtil;
import com.newsee.remote.common.utils.tools.DateUtils;
import com.newsee.remote.ecommerce.commerce.jingdong.service.IJdTokenService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.newsee.remote.common.utils.http.HttpClientExecutor.httpPost;
import static com.newsee.remote.common.utils.tools.EncryptUtil.getMD5Str;

/**
 * @author liangzhi.chen
 * @description 获取京东token
 * @date 2019/8/9 上午 09:29
 **/
@Service
@Slf4j
public class JdTokenServiceImpl implements IJdTokenService {

    /**
     * grant_type 固定为access_token
     */
    private final static String GRANT_TYPE = "access_token";

    /**
     * 账号
     */
    @Value("${jdUserName}")
    private String jdUserName;

    /**
     * m密码
     */
    @Value("${jdPassword}")
    private String jdPassword;

    /**
     * client_id
     */
    @Value("${jdClientId}")
    private String jdClientId;

    /**
     * clientSecret
     */
    @Value("${jdClientSecret}")
    private String jdClientSecret;

    /**
     * 获取token url
     */
    @Value("${jdGetTokenUrl}")
    private String jdGetTokenUrl;


    @Override
    public String getToken() {
        String token = StringUtils.EMPTY;
        Object o = ConcurrentHashMapCacheUtil.get(EcommerceEnum.E_JINGDON.getDesc());
        if (null != o) {
            token = o.toString();
            return token;
        }

        Map<String, String> params = new HashMap<>(6);
        // 固定值 access_token
        params.put("grant_type", GRANT_TYPE);
        // 用户名
        params.put("username", jdUserName);
        // 加密后的密码
        String password = getMD5Str(jdPassword).toLowerCase();
        params.put("password", password);
        // 当前时间 格式yyyy-MM-dd HH:mm:ss
        String timestamp = DateUtils.format(new Date(), DateUtils.STRING_PATTERN_FULL);
        params.put("timestamp", timestamp);
        // 对接账号
        params.put("client_id", jdClientId);
        // 对接账号密钥
        String clientSecret = jdClientSecret;
        // 认证标识
        String sign = clientSecret + timestamp + jdClientId + jdUserName + password + GRANT_TYPE + clientSecret;
        sign = getMD5Str(sign).toUpperCase();
        params.put("sign", sign);
        // 执行请求
        String response = httpPost(jdGetTokenUrl, params);

        try {
            //解析结果
            JSONObject jsonReturn = JSON.parseObject(response);
            if (null != jsonReturn) {
                Boolean success = jsonReturn.getBoolean("success");
                if (success) {
                    JDtokenDTO jDtokenDTO = JSON.parseObject(jsonReturn.getString("result"), JDtokenDTO.class);
                    String accessToken = jDtokenDTO.getAccess_token();
                    ConcurrentHashMapCacheUtil.put(EcommerceEnum.E_JINGDON.getDesc(), accessToken);
                    token = accessToken;
                } else {
                    log.error("解析京东token失败：" + jsonReturn.toJSONString());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析京东token失败：" + e.getMessage());
        }

        return token;
    }
}
